package com.czh.subject.common.context;



import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户上下文信息工具类
 * @author caozaihui
 * @version 1.0
 * @since 2024/9/7 下午 10:07
 */

public class UserContextHandler {
    private static final InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL = new InheritableThreadLocal<>();

    public static Object get(String key) {
        Map<String, Object> map = getLocalMap();
        return map.get(key);
    }
    public static void set(String key, Object value) {
        Map<String,Object> map = getLocalMap();
        map.put(key, value);
    }
    public static void  remove(){
        THREAD_LOCAL.remove();
    }
    public static Map<String,Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (Objects.isNull(map)){
            //选用线程安全的ConcurrentHashMap
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }
}
